<template>
	<view>

		<view class="mask" v-if='showMoremask'>
			<view class="tips_join" style="position:relative">
				<view class="" style="display: flex;align-items: center;">
					<image src="../../static/images/tip.png" style="width:40rpx;height:40rpx" mode=""></image>
					<text style="font-size: 16px;font-weight: bold;margin-left: 10rpx;color: #FF5310;">温馨提示</text>
				</view>

				<view class="" style='position:absolute;right:18rpx;top:20rpx;display:flex;font-size:24rpx'>
					<!-- <view class="" @click="addSymptom">
						填写症状
					</view> -->
					<view class="" style="margin-left:50rpx">
						<image src="../../static/images/x.png" mode="" style="width:40rpx;height:40rpx"
							@click='showMoremask=false'></image>
					</view>
				</view>
			</view>
			<view class="content" style="height: 500rpx;overflow: auto;width:100%;color:#0052d9">
				
				<view v-for="(ele,idx) in msgList" :key='idx'
				
					style="display: flex;align-items: center;justify-content: space-between;margin-top:12rpx"
					
						        :class="{
						            'jiayi': ele.message.includes('加衣'),
						            'jianyi': ele.message.includes('减衣'),
						            'yichang': ele.message.includes('异常'),
						            'chuhan': ele.message.includes('出汗'),
									'dianliang': ele.message.includes('电量')
						        }"

					>
					<view class="timer" style="display: flex;align-items: center;">

						<view class="" style="width:100rpx">
							{{ele.createTime.substring(11,ele.createTime.length-3)}}
						</view>
						<view  v-if="ele.message.includes('电量')" class="" style="margin-left:80rpx;width:100rpx;">
							{{ ele.updateBy}}%
						</view>
						<view  v-else class="" style="margin-left:80rpx;width:100rpx;">
							{{ Number(ele.updateBy).toFixed(1)}}℃
						</view>
					</view>
					<view class="" style='font-size:14px'>
						{{ele.message}}
					</view>
				</view>
			</view>


		</view>
		<view class="title_main">
			知冷暖健康
		</view>

		<view class="first_join" style="display: flex;justify-content: space-between;">
			<view class="Infromation">
				<view class="portrait_join" @click="information">
					<!-- <image :src="deviceInfo.headurl" mode=""></image> -->
					<image src="../../static/images/default_avatar.jpg" mode=""></image>
				</view>
				<view class="data_join" style="margin-left:-220px">
					<text >{{deviceInfo.name}}</text>
					<!-- <text style="font-size: 13px;color: #666;position: absolute;left: -40%;top: 50%;"></text> -->
				<!-- 	<view @click="goDemo" class="" style="width:120rpx;height:40rpx;border-radius: 6rpx;background-color: #007AFF;font-size:12px;text-align:  center;line-height: 40rpx;color:#fff;position: absolute;margin:-20rpx 0 0 -30rpx">
						蓝牙测试
					</view> -->
				</view>
			</view>
			<view class="" style="display: flex;">
				<view class="History" @click="symptom" v-if='showSym'>
					<image src="../../static/images/symptom-icon.png" mode=""></image>
					<view>宝宝症状</view>
				</view>
				<view class="History" @click="histroy">
					<image src="https://srmzln.oss-cn-hangzhou.aliyuncs.com/znl/images/history.png" mode=""></image>
					<view>历史数据</view>
				</view>
			</view>
		
			<!-- <text>历史数据</text> -->
		</view>
		<view class="echarts-wrap" style="width:100%;height:600rpx;margin-top:-15rpx"
			v-show='temperature||temperature===0'>
			<uni-ec-canvas class="uni-ec-canvas" id="line-chart" ref="canvas" canvas-id="lazy-load-chart" :ec="ec">
			</uni-ec-canvas>

			<view v-show='temperature||temperature===0' style='width:100%;text-align: center;color:#999;margin-top:-52rpx;font-size: 22px;'>{{min}}分钟前 <span style='font-variant-ligatures: size:22px;color:#f91d14;margin-left:5px;'>({{getNowTime()}})</span></view>
		</view>
		<view class="container" v-if='!temperature&&temperature!==0'>
			<!-- 	<canvas canvas-id="firstCanvas" type="2d" id="firstCanvas" style="width:320px;height:320px;"></canvas> -->


			<view class="percentage">
				<!-- 	<view v-if='temperature||temperature===0'>当前温度</view> -->

				<!-- 	<view v-show='temperature||temperature===0'>({{min}}分钟前)</view> -->
				<!-- <image v-if='temperature||temperature===0' style="width: 30rpx;height: 36rpx;margin-right: 5rpx;"
					src="https://srmzln.oss-cn-hangzhou.aliyuncs.com/znl/images/sweat.png" mode=""></image>
 -->
				<!-- 
				<view class="Centigrade" :style="{color: chartColor}" v-show='temperature||temperature===0'>
					<view style="position: absolute;right: -15%;top: 180%;font-size: 36rpx;">℃</view>
				</view>
				<view class="temperature" v-if='temperature||temperature===0' :style="{color: chartColor}">
					{{temperature}}
				</view> -->
				<view class="temp" :style="{color: chartColor}" v-if='!noDevice'>暂无当天数据</view>
				<view class="temp" :style="{color: chartColor}" v-else>暂未绑定设备！</view>
				<!-- <image v-if='temperature||temperature===0'
					style="width: 24rpx;height: 30rpx;margin-right: 5rpx;margin-top: 10rpx;"
					src="https://srmzln.oss-cn-hangzhou.aliyuncs.com/znl/images/sweat.png" mode=""></image>

				<text v-if='temperature||temperature===0' style="color: #666666;">出汗程度:</text><text
					style="color: #FFD010;">{{waterData}}</text> -->
			</view>
		</view>
		<!-- 	<view class="time_join">
			{{lasttime}}
		</view>
 -->
		<!-- 状态 -->
		<view class="state">
			<!-- 设备型号 -->
			<view class="model_join">
				<!-- <image src="https://srmzln.oss-cn-hangzhou.aliyuncs.com/znl/images/model.png" mode=""></image> -->
				<view class="" style="font-size:16px">
					型号
				</view>
				<view class="" style="font-size:28rpx">
					{{model}}
				</view>
			</view>
			<!-- 在线状态 -->
			<view class="line_join" style="font-size:28rpx">
				<u-icon name="wifi" color="#596FE8" v-show="isOnline" size="40"></u-icon>
				<u-icon name="wifi-off" color="#596FE8" v-show="!isOnline" size="40"></u-icon>
				<view v-show="isOnline">
					在线
				</view>
				<view v-show="!isOnline">
					离线
				</view>
			</view>
			<!-- 剩余电量 -->
			<view class="quantity_join" style="font-size:28rpx">
				<!-- <JohnElectric percentage="100" v-if='quantity>=15'></JohnElectric> -->
						<JohnElectric :percentage="quantity" ></JohnElectric>
				<view style="padding-top: 10rpx;" v-if='quantity>=15'>
					电量:{{quantity}}%<!-- <text v-show='quantity!=="未知"'>%</text> -->
				</view>
				<view style="padding-top: 10rpx;color:red" v-else>
					电量:{{quantity}}%<!-- <text v-show='quantity!=="未知"'>%</text> -->
				</view>
			</view>
			<!-- 声音状态  -->
		<!-- 	<view class="voice_join" style="font-size:28rpx;filter: grayscale(.95)">
				<u-icon name="volume-up" color="#596FE8" v-show="showUpImg" @click="changeImg" size="40"></u-icon>
				<u-icon name="volume-off" color="#596FE8" v-show="!showUpImg" @click="changeImg" size="40"></u-icon>
				<view v-show="showUpImg">
					声音:开
				</view>
				<view v-show="!showUpImg">
					声音:关
				</view>

			</view> -->
		</view>
		<!-- 提示	 -->
		<view class="Tips">
			<view class="tips_join" style="position:relative">
				<view class="" v-if='showTips'
					style="padding:20rpx 18rpx;color:#999;font-size:26rpx;text-align:left;position:absolute;right:50rpx;width:400rpx;height:140rpx;border-radius: 5rpx;background: #fff;z-index:999;box-shadow: 0px 0px 15rpx 15rpx #f1f1f1;margin-top:46rpx">
					<view class="">
						A.温度小于32，提示加衣；
					</view>
					<view class="">
						B.温度小于37，提示减衣；
					</view>
					<view class="">
						C.温湿大于90，提示换内衣；
					</view>
				</view>
				<view class="" style="display: flex;justify-content: space-between;align-items: center;">
					<view class="" style="display: flex;align-items: center;">
						<image src="../../static/images/tip.png" style="width:40rpx;height:40rpx" mode=""></image>
						<text style="font-size: 16px;font-weight: bold;margin-left: 10rpx;color: #FF5310;" @click='goNewHome'>温馨提示</text>
					</view>
					<view class="" style="display: flex;align-items: center;">
						<view class="" @click='buy' style='font-size:32rpx'>
							如何购买
						</view>
					<!-- 	<view class="" @click="getMsgList" style='font-size:32rpx;margin-left:20rpx'>
							查看更多
						</view> -->
					</view>
				</view>

				<view v-if="timeOutTips" class="" style='margin-top:36rpx;color:1890ff;font-size:46rpx'>
					{{timeOutTips}}
				</view>
				<view v-if="!timeOutTips&&temperature&&temperature<=31&&humidity<90" :class="outTime?'outTime-class':''"
					style='margin-top:36rpx;color:1890ff;font-size:46rpx;color:#2397ee'>
					宝宝体表温度偏低,请酌情加衣</view>
				<view v-if="!timeOutTips&&temperature&&temperature>=37&&humidity<90" :class="outTime?'outTime-class':''"
					style='margin-top:36rpx;color:1890ff;font-size:46rpx;color:#f91d14'>宝宝体表温度偏高,请酌情减衣
				</view>
				<view v-if="!timeOutTips&&temperature&&temperature<37&&temperature>31&&humidity<90" :class="outTime?'outTime-class':''"
					style='margin-top:36rpx;color:1890ff;font-size:46rpx;color:#16af19'>宝宝体表温湿度正常
				</view>
				<view v-if="humidity>90&&!timeOutTips&&temperature<37&&temperature>31" :class="outTime?'outTime-class':''"
					style='margin-top:36rpx;color:1890ff;font-size:46rpx;color:#f91d14'>
					宝宝可能出汗，请酌情更换衣物
				</view>
			
				<view class=""
					style="font-size:26rpx;color:#999;position: absolute;bottom:16rpx;left:180rpx;margin-top:10rpx">
					如实际情况不符，请忽略此次提醒。
				</view>
				<view class="" style='position:absolute;right:18rpx;top:12rpx;display:flex;font-size:28rpx'>
				
				</view>
			</view>
		</view>
		<!-- 	<view class="" style='width:160rpx;background:#999999;color:#fff;height:50rpx;text-align: center;line-height:50rpx;border-radius: 5rpx;margin-left:20rpx' @click="addSymptom">
			添加症状
		</view> -->
	</view>

</template>



<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import uniEcCanvas from '@/components/uni-ec-canvas/uni-ec-canvas'
	import * as echarts from '@/components/uni-ec-canvas/echarts.min.js'
	var CRC = {};
	
	CRC._auchCRCHi = [
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
	  0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
	  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
	  0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
	  0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
	  0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
	  0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
	];
	CRC._auchCRCLo = [
	  0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
	  0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
	  0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
	  0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
	  0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
	  0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
	  0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
	  0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
	  0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
	  0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
	  0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
	  0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
	  0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
	  0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
	  0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
	  0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
	  0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
	  0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
	  0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
	  0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
	  0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
	  0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
	  0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
	  0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
	  0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
	  0x43, 0x83, 0x41, 0x81, 0x80, 0x40
	];
	
	CRC.CRC16 = function (buffer) {
	  var hi = 0xff;
	  var lo = 0xff;
	  for (var i = 0; i < buffer.length; i++) {
	    var idx = hi ^ buffer[i];
	    hi = (lo ^ CRC._auchCRCHi[idx]);
	    lo = CRC._auchCRCLo[idx];
	  }
	  return CRC.padLeft((hi << 8 | lo).toString(16).toUpperCase(), 4, '0');
	};
	
	CRC.isArray = function (arr) {
	  return Object.prototype.toString.call(arr) === '[object Array]';
	};
	
	CRC.ToCRC16 = function (str) {
	  return CRC.CRC16(CRC.isArray(str) ? str : CRC.strToByte(str));
	};
	
	CRC.ToModbusCRC16 = function (str) {
	  return CRC.CRC16(CRC.isArray(str) ? str : CRC.strToHex(str));
	};
	
	CRC.strToByte = function (str) {
	  var tmp = str.split(''), arr = [];
	  for (var i = 0, c = tmp.length; i < c; i++) {
	    var j = encodeURI(tmp[i]);
	    if (j.length == 1) {
	      arr.push(j.charCodeAt());
	    } else {
	      var b = j.split('%');
	      for (var m = 1; m < b.length; m++) {
	        arr.push(parseInt('0x' + b[m]));
	      }
	    }
	  }
	  return arr;
	};
	
	CRC.convertChinese = function (str) {
	  var tmp = str.split(''), arr = [];
	  for (var i = 0, c = tmp.length; i < c; i++) {
	    var s = tmp[i].charCodeAt();
	    if (s <= 0 || s >= 127) {
	      arr.push(s.toString(16));
	    }
	    else {
	      arr.push(tmp[i]);
	    }
	  }
	  return arr;
	};
	
	CRC.filterChinese = function (str) {
	  var tmp = str.split(''), arr = [];
	  for (var i = 0, c = tmp.length; i < c; i++) {
	    var s = tmp[i].charCodeAt();
	    if (s > 0 && s < 127) {
	      arr.push(tmp[i]);
	    }
	  }
	  return arr;
	};
	
	CRC.strToHex = function (hex, isFilterChinese) {
	  hex = isFilterChinese ? CRC.filterChinese(hex).join('') : CRC.convertChinese(hex).join('');
	
	  //清除所有空格
	  hex = hex.replace(/\s/g, "");
	  //若字符个数为奇数，补一个空格
	  hex += hex.length % 2 != 0 ? " " : "";
	
	  var c = hex.length / 2, arr = [];
	  for (var i = 0; i < c; i++) {
	    arr.push(parseInt(hex.substr(i * 2, 2), 16));
	  }
	  return arr;
	};
	
	CRC.padLeft = function (s, w, pc) {
	  if (pc == undefined) {
	    pc = '0';
	  }
	  for (var i = 0, c = w - s.length; i < c; i++) {
	    s = pc + s;
	  }
	  return s;
	};
	export default {
		components: {
			uniEcCanvas,
		},
		data() {
			return {
				needSameTime:false,
				noDevice:false,
				outTime:false,
				showSym:false,
				lyid:'',
				list: [],
				deviceId: '',
				servicesId: '',
				notifyId: '',
				writeId: '',
				balanceData: '',
				hexstr: '',
				readId: '',
				deviceInfo: [],
				data: [],
				blueDataArr:[],
				value:'',
				msgList: [],
				timeOutTips: '',
				isOnline: false,
				showTips: false,
				showMoremask: false,
				humidity: '',
				iscd: null,
				waterData: '',
				quantity: '', //剩余电量
				temperature: '', //温度值
				chartColor: '', //图表颜色
				showUpImg: true,
				name: '宝宝',
				min: 1,
				showUp: true,
				model: 'X001',
				lasttime: '',
				headurl: 'https://srmzln.oss-cn-hangzhou.aliyuncs.com/znl/images/portrait.png',
				status: 0,
				maxtemp: 0,
				mintemp: 0,
				avgtemp: 0,
				maxt: 0,
				mint: 0,
				deviceInfo: {},
				scene: '',
				query: '',
				ec: {
					lazyLoad: true,
					option: {
						series: [{
								type: 'gauge',
								hoverAnimation: false,
								center: ['50%', '54%'],
								radius: '105%',
								// startAngle: 225,
								// endAngle: 16,
								min: 23,
								max: 43,
								axisLine: {
									lineStyle: {
										width: 25,
										color: [
											[0.333, '#2397ee'],
											[0.666, '#16af19'],
											[1, '#f91d14']
										]
									}
								},
								pointer: {
									show: false,
									itemStyle: {
										color: 'auto'
									}
								},
								axisTick: {
									distance: -30,
									length: 14,
									splitNumber: 2,
									lineStyle: {
										color: '#fff',
										width: 2,

									}
								},
								splitLine: {
									distance: -30,
									length: 30,
									lineStyle: {
										color: '#fff',
										width: 1
									}
								},
								axisLabel: {
									color: 'auto',
									distance: 40,
									fontSize: 15
								},
								detail: {
									fontSize: 58,
									offsetCenter: [0, '20%'],
									valueAnimation: true,
									formatter: ['{value}℃', '{a|无汗}'].join('\n'),
									padding: [-80, 0, 0, 0],
									rich: {
										a: {
											color: '#16af19',
											fontSize: 42,
											fontWeight: 'bold',
											padding: [70, 0, 10, 0],

										},
										b: {
											color: '#16af19',
											fontSize: 38,
											fontWeight: 'bold',
											padding: [90, 0, 10, 0],
										}
									},
									color: 'auto'
								},
								data: [{
									value: 30
								}]
							},
							{
								//内圆
								type: 'pie',
								radius: '0%',
								silent: false,
								center: ['50%', '50%'],
								z: 0,
								itemStyle: {
									normal: {
										color: new echarts.graphic.RadialGradient(
											0.5,
											0.5,
											1,
											[{
													offset: 0,
													color: 'rgba(17,24,43,0)'
												},
												{
													offset: 0.5,
													// color: '#1E2B57'
													color: 'rgba(28,42,91,.6)'
												},
												{
													offset: 1,
													color: '#141C33'
													// color:'rgba(17,24,43,0)'
												}
											],
											false
										),
										label: {
											show: false
										},
										labelLine: {
											show: false
										}
									}
								},
								hoverAnimation: false,
								label: {
									show: false
								},
								tooltip: {
									show: false
								},
								data: [100]
							},
							{
								tooltip: {
									show: false
								},
								name: 'wrap',
								z: 1,
								type: 'pie',
								hoverAnimation: false,
								legendHoverLink: false,
								center: ['50%', '80%'],
								radius: ['0%', '90%'],
								startAngle: 0,
								label: {
									normal: {
										show: false,
										position: 'center'
									},
									emphasis: {
										show: false
									}
								},
								labelLine: {
									normal: {
										show: false
									}
								},
								data: [{
										value: 50,
										itemStyle: {
											normal: {
												color: '#fff'
											},
											emphasis: {
												color: '#fff'
											}
										}
									},
									{
										value: 50,
										name: '1',
										itemStyle: {
											normal: {
												color: 'transparent'
											}
										}
									}
								]
							}
						]
					}


				}
			}
		},
		onLoad(options) {
			this.getTimer()
			wx.showShareMenu({
				withShareTicket: true,
				//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus: ["shareAppMessage", "shareTimeline"]
			})
			// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
			if (options.q) {
				let q = decodeURIComponent(options.q);
				const tid = this.getQueryString(q, 'tid');
				console.log(tid, 11);
				const code = this.getQueryString(q, 'code');
				const postId = this.getQueryString(q, 'hbid')
				const artileId = this.getQueryString(q, 'wzid')
				const developer = this.getQueryString(q, 'developer')
				const no = this.getQueryString(q, 'no')
				console.log(code, 22);
				if (code) {
					uni.navigateTo({
						url: '/pages/login/login?code=' + code
					})
					// uni.navigateTo({
					// 	url: '/pages/login/binding/device/device?code=' + code
					// })
				} else if (developer) {
					uni.navigateTo({
						url: '/pages/login/login?postId=' + postId + '&artileId=' + artileId + '&developer=' +
							developer
					})
				} else if (postId && artileId) {
					uni.navigateTo({
						url: '/pages/login/login?postId=' + postId + '&artileId=' + artileId
					})
				} else if (artileId) {
					uni.navigateTo({
						url: '/pages/login/login?artileId=' + artileId
					})
				} else if (postId) {
					uni.navigateTo({
						url: '/pages/login/login?postId=' + postId
					})
				}else if(no){
					uni.navigateTo({
						url: '/pages/login/login?no=' + no
					})
				}
			} else {
				let zwxphone = wx.getStorageSync("zwxphone");
				let _this = this;
				if (!zwxphone) {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				} else {
					let tpl_param = {
						phone: zwxphone
					};
					// console.log(uni.getStorageSync('loginPageRedic'), 11)
					// this.getSweat()
					this.wxLogin(tpl_param)
					// this.lastDeviceInfo();
					// this.times(); //加载定时任务
				}
			}
			// this.scene = scene
			// this.query = query.toString()
			//类型为string，所以只能判断不叫"undefined"
			//console.log(typeof(scene));
			// if (scene != "undefined" && scene.length > 4) {
			// 	console.log(scene);
			// 	uni.showModal({
			// 		content: '证书编码:' + scene + '，点击查询查看详情',
			// 		showCancel: false
			// 	});
			// 	this.certNumber = scene;
			// } else {
			// 	console.log("没有启动参数");
			// 	// this.lastDeviceInfo();
			// }

		},
		onReady() {

			setTimeout(() => {
				console.log(this)
				console.log(this.$refs)
				this.$refs['canvas'].init()
				console.log('延迟加载了')
			}, 1000) // 两秒之后延迟加载  

			// setTimeout(() => {
			//this.ec.option.series[0].data = [120, 132, 101, 134, 90, 230, 210]  
			// this.ec.option.xAxis[0].data = [1,2,3,4,5,6,7]  
			// 如果是data数组内的数据 记得用$set  
			// 	console.log('数据更改了')
			// }, 2000)
		},
		computed: {
			...mapState(['wxuserInfo', 'isNewUser']),
		},
		methods: {
			async wxLogin(tpl_param) {
				let res = await this.$api.wxlogin(tpl_param);
				if (res.code == 200) {
	
			wx.setStorageSync('zwxphone', res.result.phone);
			wx.setStorageSync('loginPageRedic', true);
			wx.setStorageSync('token',res.result.token)
				this.lastDeviceInfo();
				this.times(); //加载定时任务
				this.getDevice()
							
				} 
			
			},
			
			getNowTime(){
				const  now = new Date()
				const hours = ('0'+now.getHours()).slice(-2)
				const minutes = ('0'+now.getMinutes()).slice(-2)
				return hours + ':' + minutes
			},
			getDevice(){
				this.$api.getDeviceList().then(res => {
					let list = []
					if (res.code === 200) {
						list = res.result.list
						if(list.length){
						list.forEach(ele => {
							if (ele.deviceStatus === 'Y') {
								this.deviceInfo = ele
								this.initBlue()
								// setTimeout(()=>{
								// 	wx.stopBluetoothDevicesDiscovery({
								// 		success: function() {
								// 			console.log('60s之后关闭蓝牙搜索,避免耗电');
								// 		}
								// 	})
								// },60000)
									// this.uploadData()
							}
						})
						}
					}
				})
			},
			
			// uploadData(){
			// 	const params = {
			// 		deviceid:this.deviceInfo.device_code,
			// 		devices:[{timer:'2023-06-06 13:15:00',temp1:33.2,humidity:45.2,power:32,xdata:223,ydata:234,zdata:321,crcData:134},{timer:'2023-06-06 13:16:00',temp1:33.2,humidity:45.2,power:32,xdata:223,ydata:234,zdata:321,crcData:134}]
			
			// 	}
			// 		this.$api.uploadBlueToothData(params)
			// },
			goDemo(){
				console.log(5555)
			// uni.navigateTo({
			// 	url: '/pages/index/home/home'
			// })
			uni.navigateTo({
				url:'/pages/index/blue-tooth/blue-tooth'
			})
			},
			goNewHome(){
				console.log(2111)
				uni.navigateTo({
					url: '/pages/index/home/home'
				})
			},
			buy() {
				uni.showModal({
					title: '知冷暖',
					content: '前往淘宝店铺-知冷暖健康或淘宝直接搜索知冷暖幼儿购买',
					showCancel: true,
					success: (res) => {
						if (res.confirm) {
							console.log(1111)

							
							uni.navigateTo({
								url: '/pages/index/webview/webview'
							})
						}
					}
				})
			},
			getMsgList() {
				this.$api.getMsgList({
					deviceCode: this.deviceInfo.device_code
				}).then(res => {
					if (res.code === 200) {
						this.showMoremask = true
						const list = res.result.list
						const arr = []
						if(list.length){
							list.forEach(ele=>{
								if(ele.updateBy!=='0.0')
								{
									arr.push(ele)
								}
							})
						}
						this.msgList = arr
					}
				})
			},
			getSweat(humidity) {
				this.$api.getDeviceList().then(res => {
					let list = []
					if (res.code === 200) {
						list = res.result.list
						if (!list.length) {
							// uni.navigateTo({
							// 	url: '/pages/login/login'
							// })
							this.noDevice = true
							return
						}
						list.forEach(ele => {
							if (ele.deviceStatus === 'Y') {
								this.deviceInfo = ele
							
							
								if (humidity) {
									this.$api.searchDeviceSweat({
										deviceNo: ele.code
									}).then(response => {
										if (response.code === 200) {
											console.log(humidity, 9958)
											this.$refs['canvas'].init()
											this.ec.option.series[0].detail.formatter = [
												'{value}℃', `{a|${response.message}}`,
												`{b|${humidity}%}`
											].join('\n')
											if (response.message !== '无汗') {
												this.ec.option.series[0].detail.rich.a.value = '11'
												this.ec.option.series[0].detail.rich.a.color =
													'#f91d14'
												this.ec.option.series[0].detail.rich.b.color =
													'#f91d14'
											}
										}
									})
								}
							}
						})
					}
				})
			},
			onPullDownRefresh() {
				console.log(119)
				this.lastDeviceInfo()
				
				if(this.deviceId){
					this.noticeData()
				}else{
				this.initBlue()
				}
			},
			getQueryString(url, name) {
				var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
				var r = url.substr(1).match(reg)
				if (r != null) {
					return r[2]
				}
				return null;
			},
			getTimer() {
				var myDate = new Date();
				var myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
				var myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
				var myToday = myDate.getDate(); //获取当前日(1-31)
				var myDay = myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
				var myHour = myDate.getHours(); //获取当前小时数(0-23)
				var myMinute = myDate.getMinutes(); //获取当前分钟数(0-59)
				var mySecond = myDate.getSeconds(); //获取当前秒数(0-59)
				if (myHour < 10) {
					myHour = `0${myHour}`
				}

				if (myMinute < 10) {
					myMinute = `0${myMinute}`
				}
				this.lasttime = myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + '-' + myDate.getDate() + ' ' +
					myHour + ':' + myMinute
			},
			async lastDeviceInfo() {
				// let tpl_param = {
				// 	pageId: "f945d0c61ab6457b89ac05e035bb4d39"
				// };
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let res = await this.$api.lastDeviceInfo();
				console.info(res);
				// if(res.status != undefined && res.status==500)
				// {
				// 	uni.reLaunch({
				// 		url: '/pages/login/login'
				// 	});
				// }else	
				wx.stopPullDownRefresh()
				
				if (res.code == 200) {
					// console.log(res);
					this.name = res.result.name;
					this.quantity = res.result.quantity;
					this.lasttime = res.result.lasttime;
					this.temperature = res.result.temperature;
					this.min = res.result.min;
					this.showUpImg = res.result.showUpImg;
					this.showUp = res.result.showUp;
					this.model = res.result.model;
					this.status = res.result.status;
					this.mintemp = res.result.mintemp;
					this.avgtemp = res.result.avgtemp;
					this.maxt = res.result.maxt;
					this.mint = res.result.mint;
					this.waterData = res.result.waterData
					this.humidity = res.result.humidity
					if(this.temperature>44){
						this.temperature=43.9
					}else if(this.temperature<20){
						this.temperature = 20.1
					}
					if(this.humidity>100){
						this.humidity= 100
					}
					// this.animation(this.temperature);

					this.ec.option.series[0].data[0].value = this.temperature.toFixed(1)
					// this.ec.option.series[0].formatter = ['{value}℃', '{a|当前温度}'].join('\n')

					// this.ec.option.series[0].detail.formatter = ['{value}℃', `{a|${this.waterData}}`].join('\n')
					// if (this.waterData === '有汗') {
					// 	this.ec.option.series[0].detail.rich.a.color = '#f91d14'
					// }
					this.getSweat(res.result.humidity)
			
					const now = new Date().getTime()
					const timer = Date.parse(this.lasttime)
					if (now - timer > 3600000) {
						// this.timeOutTips = '设备好像不在工作，请检查！'
						// this.isOnline = false
						// this.quantity = '未知'
						this.ec.option.series[0].detail.color = 'grey'
						this.outTime = true

					} else if (now - timer > 1200000) {
						// this.timeOutTips = '设备网络状态不好，请检查！'
						// this.isOnline = false
						// this.quantity = '未知'
						this.ec.option.series[0].detail.color = 'grey'
						this.outTime = true
					} else {
						this.outTime = false
						// this.isOnline = true
						this.timeOutTips = ''
						this.quantity = res.result.quantity
						this.ec.option.series[0].detail.color = 'auto'
						if (res.result.iscd && res.result.iscd != 0 && res.result.iscd != 1) {
							if (res.result.iscd == 2) {
								// this.timeOutTips = '充电中'
								// this.quantity = res.result.quantity;
							} else if (res.result.iscd == 3 && this.temperature==0) {
								// this.timeOutTips = '电量已充满'
								// this.quantity = res.result.quantity;
							}
						}
					}
					console.log(now, 11, timer)


				
				} else {
					this.getSweat()
					// if (this.deviceInfo.status === '1') {
					// 	this.isOnline = '在线'
					// }


					// uni.showModal({
					// 	title: '获取设备信息',
					// 	content: res.message || '获取最后一次数据失败',
					// 	showCancel: false
					// });

				}
				uni.hideLoading();

				//this.animation(this.temperature)
			},
			// 症状添加
			addSymptom() {
				// this.showWriteSymptom = true

				uni.navigateTo({
					url: '/pages/index/histroy/HistroyWriteSymptom'
				});
			},
			symptom(){
				uni.navigateTo({
					url:'symptom/symptom'
				})
			},
			// 历史数据
			histroy() {
				//判断有无历史数据
				let urlStr = ''
				if (true) {
					urlStr = '/pages/index/histroy/HistroyData' //有数据
				} else {
					urlStr = '/pages/index/histroy/HistroyNot' //无数据
				}
				uni.navigateTo({
					url: urlStr
				});

			},
			information() {
				uni.navigateTo({
					url: 'equipmentInformation/equipmentInformation'
				})
			},
			async changeImg() {
				return
				this.showUpImg = !this.showUpImg;
				let tpl_param = {
					isbeep: this.showUpImg
				};
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let res = await this.$api.updateIsbeep(tpl_param);
				if (res.code == 200) {

				} else {
					uni.showModal({
						content: res.message || '获取最后一次数据失败'
					});
				}
				uni.hideLoading();
			},

			async change() {
				this.showUp = !this.showUp;
				let tpl_param = {
					status: this.showUp
				};
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let res = await this.$api.updateCloseStatus(tpl_param);
				if (res.code == 200) {

				} else {
					uni.showModal({
						content: res.message || '获取最后一次数据失败'
					});
				}
				uni.hideLoading();
			},
			animation(temperature) {
				const query = uni.createSelectorQuery()

				let color = '';
				console.info(temperature + '  ' + this.mint + ' ' + this.maxt);
				if (temperature >= this.mint && temperature <= this.maxt) {
					//绿色
					color = '#008000';
				} else if (temperature < this.mint) {
					//蓝色
					color = 'rgb(67,91,221)';
				} else {
					//红色
					color = '#FF0000';
				}
				this.chartColor = color
				query.select('#firstCanvas')
					.fields({
						node: true,
						size: true
					})
					.exec((res) => {
						const canvas = res[0].node
						let ctx = canvas.getContext('2d')
						let obj = {
							width: 300,
							height: 300,
							dx: 20, // 刻度宽度
							dy: 2, // 刻度高度
							num: 60, // 刻度条数
							r: 110, // 半径
							start: -90, // 开始角度，与结束角度相对称
							progress: Math.floor(temperature * 100 / 55 + 25 * 100 / 60), // 显示进度 （单位百分比）
							index: 25, // 开始刻度
							defaultColor: '#dee1e4', // 开始颜色
							activeColor: color // 进度条颜色
						};
						this.process = obj.progress
						obj.deg = (180 - 2 * obj.start) / obj.num;
						canvas.width = obj.width;
						canvas.height = obj.height;

						for (var x = 0; x < obj.num; x++) { //灰色刻度线
							draw(x, obj.defaultColor);
						}

						function draw(x, color) { // 画出环形刻度线
							ctx.save();
							var deg = Math.PI / 180 * (obj.start + obj.deg * x); // 角度换算弧度
							var offsetY = -(Math.sin(deg) * obj.r); // 计算刻度Y轴位置
							var offsetX = -(Math.cos(deg) * obj.r); // 计算刻度X轴位置
							ctx.fillStyle = color;
							ctx.translate(obj.width / 2 - offsetX, obj.height / 2 - offsetY); // 修改画布坐标原点
							ctx.rotate(deg); // 旋转刻度
							ctx.fillRect(0, 0, obj.dx, obj.dy); // 画出刻度
							ctx.restore();
						}

						function animate(s, time) {
							if (obj.progress == 0) { // 进度为0直接退出函数
								return false;
							}
							draw(s, obj.activeColor);

							var num = obj.progress * (obj.num / 100); //格数计算

							var timmer = setTimeout(function() {
								obj.index = s + 1;

								if (s >= num) {
									clearTimeout(timmer);
								} else {
									if (s > num - 10) { // 剩余10格动画减速
										animate(obj.index, time + 20);
									} else {
										animate(obj.index, time);
									}

								}
							}, time)
						}
						animate(obj.index, 10)
					})
			},
			times() { //定义了一个times()方法来执行定时查询findDB()
				return setInterval(() => { //setInterval换个名字就行了
					this.lastDeviceInfo()
					
					if(this.deviceId){
						this.noticeData()
					}else{
					  this.initBlue()
					}
					// uni.reLaunch({
					// 	url: '../index/index'
					// })
				}, 60000 * 1); //设置时间，这里是1分钟
			},
			today() {
				var myDate = new Date();
				var year = myDate.getFullYear(); //获取当前年
				var mon = myDate.getMonth() + 1; //获取当前月
				if (mon < 10) {
					mon = "0" + mon;
				}
				var date = myDate.getDate(); //获取当前日
				if (date < 10) {
					date = "0" + date;
				}
				var hours = myDate.getHours(); //获取当前小时
				if (hours < 10) {
					hours = "0" + hours;
				}
				var minutes = myDate.getMinutes(); //获取当前分钟
				if (minutes < 10) {
					minutes = "0" + minutes;
				}
				var seconds = myDate.getSeconds(); //获取当前秒
				if (seconds < 10) {
					seconds = "0" + seconds;
				}
				let dates = year + "-" + mon + "-"
				return dates
			
			},
			getTime(e){
				var myDate = new Date();
				var mon = myDate.getMonth() + 1; //获取当前月
				if (mon < 10) {
					mon = "0" + mon;
				}
				var date = myDate.getDate(); //获取当前日
				if (date < 10) {
					date = "0" + date;
				}
				var hours = myDate.getHours(); //获取当前小时
				if (hours < 10) {
					hours = "0" + hours;
				}
					
				var minutes = myDate.getMinutes(); //获取当前分钟
				if (minutes < 10) {
					minutes = "0" + minutes;
				}
				var seconds = myDate.getSeconds(); //获取当前秒
				if (seconds < 10) {
					seconds = "0" + seconds;
				}
				
				let timer = this.timerToHex(mon)+this.timerToHex(date)+this.timerToHex(hours)+this.timerToHex(minutes)
				// if(e){
				// 	return hours + ':' + minutes
				// }else{
				// 	return timer
				// }
				return  timer
			
			},
			timerToHex(timer) {
			
				const result =String(timer.toString(16))
				
				if (result.length> 1) {
					return result
				} else {
					return '0' + result
				}
			
			},
			stampToDate(stamp){
				    // 时间戳 
				  
				    // 此处时间戳以毫秒为单位
				    let date = new Date(parseInt(stamp));
				    let Year = date.getFullYear();
				    let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
				    let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
				    let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
				    let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
				    let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
				    let  GMT =  Year + '-' + Moth + '-' + Day + '   '+ Hour +':'+ Minute  + ':' + Sechond;
				    
				   return GMT // 2022-09-07 15:56:07
			},
			uploadData() {
				const day = this.today().substring(8,10)
				if(this.data.length&&this.needSameTime){
					this.data.forEach((ele,i)=>{
					const date = new Date()
					const now = Date.parse(date)
					const timer = now-(this.data.length-i)*60000
					ele.timer = this.stampToDate(timer)	
					})
					
				}
				const params = {
					deviceid: this.deviceInfo.device_code,
					devices: this.data,
					lyid:this.lyid
			
				}
				this.$api.uploadBlueToothData(params).then(res => {
					if (res.code === 200) {
						uni.hideLoading();
						console.log('111')
						this.data = []
						this.lastDeviceInfo()
					} else {
						console.log(res, 222)
					}
				})
			},
			navigateBack() {
				uni.navigateTo({
					url: '/pages/index/index'
				})
				
			},
			/**获取已授权列表*/
			getUserSetting() {
				console.log("获取已授权列表")
				var that = this;
				wx.getSetting({
					success(res) {
						var authSetting = res.authSetting
						console.log(res.authSetting)
						if (!res.authSetting['scope.bluetooth']) {
							//授权获取蓝牙权限
							wx.authorize({
								scope: 'scope.bluetooth',
								success() {
									console.log("成功获取蓝牙权限")
									that.initBlue()
								},
								fail() {
									console.log("蓝牙权限获取失败")
								}
							})
						} else {
							that.initBlue()
						}
					},
					fail(f) {
						console.log(f)
					}
				})
			},
			
			/**初始化蓝牙设备*/
			initBlue() {
				console.log("初始化蓝牙")
				var that = this;
				wx.openBluetoothAdapter({
					success: function(res) {
						that.findBlue()
					},
					fail: function(res) {
						uni.showModal({
							title: '蓝牙提示',
							content: '未开启蓝牙，请开启！'
						});
						console.log(res, "请开启蓝牙定位")
					}
				})
			},
			
			/**开始搜索蓝牙设备*/
			findBlue() {
				var that = this
				wx.startBluetoothDevicesDiscovery({
					services: [],
					allowDuplicatesKey: true,
					interval: 0,
					powerLevel: 'high',
					success: function(res) {
						console.log("开始搜索蓝牙设备", res)
						//加个延时，避免获取数据为空
						setTimeout(() => {
							that.getBlue()
						}, 300)
					}
				})
			},
			inArray(arr, key, val) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i][key] === val) {
						return i;
					}
				}
				return -1;
			},
			closeBlue() {
				let that = this
				wx.closeBluetoothAdapter({
					success:(res)=>{
						console.log('关闭适配器成功！')
						
					},
					fail:(res)=>{
						console.log('关闭适配器失败！',res)
					}
				})
				wx.closeBLEConnection({
					deviceId:this.deviceId,
					success:(res)=>{
						console.log(res,'关闭蓝牙成功!')
						
					},
					fail:(res)=>{
						console.log('关闭蓝牙失败！',res,this.deviceId)
					}
				})
			},
			
			/**获取搜索到的设备信息*/
			getBlue() {
				var that = this
				//        wx.getBluetoothDevices({
				//            success: function (res) {
				// console.log(res,111)
				//                var blueToothList = []
				// that.list = res.devices
				//                for (var i = 0; i < res.devices.length; i++) {
				//                    if (res.devices[i].name != "未知设备") {
				//                        console.log("遍历已知蓝牙设备" + i, res.devices[i].deviceId, res.devices[i].name, res.devices[i].RSSI)
				//                    }
				//                }
				//            },
				//            fail: function () {
				//                console.log("搜索蓝牙设备失败")
				//            }
				//        })
			
				wx.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						if (!device.name && !device.localName) {
							return
						}
						const foundDevices = that.list
						const idx = that.inArray(foundDevices, 'deviceId', device.deviceId);
						let str = ''
						if(device.name){
							str = device.name
						}else{
							str = device.localName
						}
					
						console.log(str,777)
						if(str===that.deviceInfo.code){
							that.isOnline = true
							that.connect(device)
							
							
						}
						if (idx === -1) {
							that.list.push(device)
							
						}
			
			
					})
					// console.log(res, 444)
			
				})
			},
			connect(item) {
				this.deviceId = item.deviceId
				this.lyid = item.name
				this.connetBlue()
			},
			/**获取到设备之后连接蓝牙设备*/
			connetBlue() {
				this.blueDataArr = []
				// this.showMask = true
				setTimeout(() => {
					//getBlue里面获取的deviceId
					var deviceId = this.deviceId
					var that = this;
					wx.createBLEConnection({
						deviceId: deviceId, //设备id
						success: function(res) {
							console.log("连接蓝牙成功!")
							wx.stopBluetoothDevicesDiscovery({
								success: function() {
									console.log('连接蓝牙成功之后关闭蓝牙搜索,避免耗电');
								}
							})
							//获取蓝牙服务ID
							that.getServiceId()
							//连接成功，开始监听蓝牙连接状态，断开后重连
							that.onStateChange()
						},
						fail: function(f) {
							console.log(f, 555)
						}
					})
				}, 200)
			},
			
			/**开始监听蓝牙连接状态*/
			onStateChange() {
				wx.onBLEConnectionStateChange(this.stateChangeFun)
			},
			
			/**蓝牙状态监听方法*/
			stateChangeFun(res) {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				var connectStatus = res.connected
				if (connectStatus == false) {
					this.isOnline = false
					console.log('蓝牙断开重连', `device ${res.deviceId} state has changed, connected: ${res.connected}`)
					this.reconnectBlue()
				}
			},
			
			/**蓝牙重连*/
			reconnectBlue() {
				var deviceId = this.deviceId
				var that = this;
				wx.createBLEConnection({
					deviceId: deviceId,
					success() {
						console.log("蓝牙重连成功！")
						that.isOnline = true
						 that.getServiceId()
							
					},
					fail() {
						that.reconnectBlue()
					}
				})
			},
			
			/**蓝牙设备的服务uuid*/
			getServiceId() {
				var that = this
				wx.getBLEDeviceServices({
					deviceId: that.deviceId,
					success: function(res) {
						console.log("蓝牙服务信息", res)
						//[0]这个服务ID下面的特征值ID有notify和write为true的，每个设备不一样，根据你的设备来，可能是[0]也可能是[1]或者其他的
						var model = res.services[0]
			
						that.servicesId = model.uuid
			
						that.getCharacteId()
					}
				})
			},
			
			/**查看蓝牙特征值*/
			getCharacteId() {
				var that = this
				wx.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.servicesId,
					success: function(res) {
						console.log("蓝牙特征值", res)
						var model = ""
						for (var i = 0; i < res.characteristics.length; i++) {
							model = res.characteristics[i]
							//接收蓝牙发送过来的数据需要这个uuid
							if (model.properties.notify == true) {
			
								that.notifyId = model.uuid
			
							}
							if (model.properties.read == true) {
			
								that.readId = model.uuid
			
							}
							//给蓝牙发送数据需要这个uuid
							if (model.properties.write == true) {
			
								that.writeId = model.uuid
							}
						}
						 that.startNotice(that.notifyId)
					}
				})
			},
			noticeData(){
				this.startNotice(this.notifyId)
			},
			/**监听蓝牙数据*/
			startNotice(uuid) {
				var that = this;
				wx.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: that.deviceId,
					serviceId: that.servicesId,
					characteristicId: uuid,
					success: function(res) {
						console.log("监听成功！ " + JSON.stringify(res))
						 that.readData()
						// console.log('1117'+that.getTimer()+'003C017C02BC01022AEE',111)
						 //that.sendOrder('0117'+that.getTimer()+'003C017C02BC01022AEE')
						 that.sendOrder('028280B1')
						// that.onBLECharacteristicValueChange()
						// setTimeout(()=>{
						// that.sendOrder('0x11')
						// },1000)
					
			
					},
					fail: function(fail) {
						console.log("蓝牙监听失败！")
					}
				})
			},
			onBLECharacteristicValueChange() {
				console.log(555)
				let that = this
				wx.onBLECharacteristicValueChange(res => {
					console.log(res, 111, JSON.stringify(res))
					let hex = Array.prototype.map.call(new Uint8Array(res.value), x => ('00' + x.toString(16))
						.slice(-2)).join('')
					console.log(hex, 999)
					console.log('监听低功耗蓝牙设备特征值变化事件成功')
					that.balanceData = that.buf2string(res.value)
					// console.log(this.balanceData,333)
					that.hexstr = that.receiveData(res.value)
					// console.log(that.hexstr,777)
			
				})
			},
			
			sameTheTime(){
				const timer = this.getTime()
				
				const crcData = '018117'+timer+'00006000fa00fa203001' + CRC.ToModbusCRC16('018117'+timer+'00006000fa00fa203001', true)
				
				console.log('发送同步时间指令',crcData,CRC.ToModbusCRC16('018117'+timer+'00006000fa00fa203001', true))
			
				 this.sendOrder(crcData)
				 this.needSameTime = false
				// this.sendOrder('0181170720215920006000fa00fa2030010B52')
			},
			oneMorePost(){
				setTimeout(()=>{
					console.log('重新连接')
					this.noticeData()
				},1000*60)
			},
			readData() {
				let that = this
				wx.onBLECharacteristicValueChange(res => {
					// console.log(that.buf2string(res.value), '16进制解析')
					// let hex = Array.prototype.map.call(new Uint8Array(res.value), x => ('00' + x.toString(16)).slice(-2)).join('')
					let hex = that.ab2hex(res.value)
					console.log(hex,676)
					if(String(hex).length<12){
						console.log('无数据，等待再一次查询')
						// that.closeBlue()
						that.oneMorePost()
						return
					}
					this.blueDataArr.push(hex)
					const num = hex.length/32
					const arr = []
					for(let i = 0;i<num;i++){
						 arr.push(hex.substring(i*32,(i+1)*32))
					}
					
					console.log(hex,88778,arr)
					if(arr.length){
						uni.showLoading({
							title: '正在上传数据',
							mask: true
						});
						arr.forEach(ele=>{
							that.decodeHex(ele)
						})
					}
					// that.sendOrder('028280B1')
					if(that.data.length && arr.length<15){
						 that.uploadData()
						 if(that.needSameTime){
							 that.sameTheTime()
						 }
						 // that.closeBlue()
							// that.noticeData()
						 // that.oneMorePost()
					}
					if(arr.length===1){
						that.oneMorePost()
					}else{
						that.noticeData()
					}
					// that.decodeHex(hex)
					// that.balanceData += that.buf2string(res.value)
					// console.log(this.balanceData,333)
					// that.hexstr = that.hexCharCodeToStr(hex)
					// console.log(that.hexstr,777)
			
				})
				wx.readBLECharacteristicValue({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.servicesId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.readId,
					success: function(res) {
						console.log('readBLECharacteristicValue:', res) // ok
					}
				})
			
			},
			decodeHex(str) {
						// const timer =
						// 	`${this.today()} ${this.parseTimer(str.substring(8,10))}:${this.parseTimer(str.substring(10,12))}:${this.parseTimer(str.substring(12,14))}`
						// const power = parseInt(str.substring(14, 16), 16)
						// const temp = parseInt(str.substring(16, 20), 16) / 10
						// const humidity = parseInt(str.substring(20, 24), 16) / 10
						// const xData = parseInt(str.substring(24, 28), 16)
						// const yData = parseInt(str.substring(28, 32), 16)
						// const zData = parseInt(str.substring(32, 36), 16)
						// const crcData = parseInt(str.substring(36, 38), 16)
						const timer =
							`${this.today()}${this.parseTimer(str.substring(6,8))} ${this.parseTimer(str.substring(8,10))}:${this.parseTimer(str.substring(10,12))}:${this.parseTimer(str.substring(12,14))}`
						let power = parseInt(str.substring(14, 16), 16)
						const temp = parseInt(str.substring(16, 20), 16) / 10
						const humidity = parseInt(str.substring(20, 24), 16) / 10
						const xData = parseInt(str.substring(24, 28), 16)
						// const yData = parseInt(str.substring(28, 32), 16)
						// const zData = parseInt(str.substring(32, 36), 16)
						const crcData = parseInt(str.substring(28, 32), 16)
						const zData = 	parseInt(str.substring(0, 4), 16)
							
						// if (!this.data.length ) {
					
							
							// wx.closeBLEConnection({
							// 	deviceId::this.deviceId,
							// 	success: function(res) {
							// 		console.log('断开蓝牙设备成功',res)
							// 	},
							// 	fail:function(res){
							// 		console.log(res)
							// 	}
							// })
							// wx.closeBluetoothAdapter({
							// 	success: function(res) {
							// 		console.log('断开成功',res)
							// 	}
							// })
						// } else {
							console.log(timer,112,temp,231,humidity,332,power)
							var date = new Date()
							const timeStamp = Date.parse(timer)
							const now = Date.parse(date)
							// if(now<timeStamp){
							// 	return
							// }
							if(power>=128){
								// this.sameTheTime()
								this.needSameTime = true
								power = power-128
							}
							// if(temp>42||temp<10||humidity>99||humidity<1){
							// 	return
							// }
							this.data.push({
								timer: timer,
								power: power,
								temp1: temp,
								humidity: humidity,
								xdata: xData,
								 ydata: 0,
								 zdata:zData,
								crcData: crcData
							})
							// this.uploadData()
							console.log(this.data.length)
						// }
					
					},
			parseTimer(timer) {
			
				const result = parseInt(timer, 16)
				console.log(timer,11,result,22)
				if (result> 9) {
					return result
				} else {
					return '0' + result
				}
			
			},
			/**发送数据*/
			sendOrder(write) {
				 let buffer = this.string2buffer(write);
				 
				   var typedArray = new Uint8Array(write.match(/[\da-f]{2}/gi).map(function (h) {
				      return parseInt(h, 16)
				    }))
				let pos = 0;
				let bytes = buffer.byteLength;
				var that = this
			
				//因为微信小程序使用蓝牙发送数据限制20字节内的原因，需要对超过20字节的数据拆包进行发送
				while (bytes > 0) {
					let tmpBuffer;
					if (bytes > 20) {
						tmpBuffer = buffer.slice(pos, pos + 20);
						pos += 20;
						bytes -= 20;
					} else {
						tmpBuffer = buffer.slice(pos, pos + bytes);
						pos += bytes;
						bytes -= bytes;
					}
					console.log(tmpBuffer, 'tmpBuffer',typedArray.buffer)
					wx.writeBLECharacteristicValue({
						deviceId: that.deviceId,
						serviceId: that.servicesId,
						characteristicId: that.writeId,
						value: typedArray.buffer,
						success: (res) => {
							console.log("写入成功", res)
							// that.onBLECharacteristicValueChange()
							  that.readData()
						},
						fail: (f) => {
							console.log("写入失败")
						}
					})
				}
			},
			buf2string(buffer) {
				var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
				return arr
					.map((char, i) => {
						return String.fromCharCode(char)
					})
					.join('')
			},
			receiveData(buf) {
				return this.hexCharCodeToStr(this.ab2hex(buf))
			},
			
			
			/**将16进制转化为ArrayBuffer*/
			string2buffer(str) {
				return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer
			},
			
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim()
				var rawStr =
					trimedStr.substr(0, 2).toLowerCase() === '0x' ?
					trimedStr.substr(2) :
					trimedStr
				var len = rawStr.length
				var curCharCode
				var resultStr = []
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16)
					resultStr.push(String.fromCharCode(curCharCode))
				}
				return resultStr.join('')
			},
			
			
			/**将ArrayBuffer转换成字符串*/
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('');
			},
			

		},
		destroyed() {
			clearInterval(this.times) //退出页面后销毁定时方法
		},
		onShareAppMessage(res) {
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: '邀请您使用知冷暖幼儿穿衣宝！', //分享的名称
				path: '/pages/index/index',
				mpId: 'wxa6957e2a04b35cb3' //此处配置微信小程序的AppId
			}
		},
		//分享到朋友圈
		onShareTimeline(res) {
			return {
				title: '邀请您使用知冷暖幼儿穿衣宝！',
				type: 0,
				summary: "",
			}
		},
		mounted() { //模板渲染之后调用的，模板渲染之前是created
			//刚进页面就能获取到findDB()中的数据
			let zwxphone = wx.getStorageSync("zwxphone");
			let _this = this;
			if (!zwxphone) {
				// uni.navigateTo({
				// 	url: '/pages/login/login'
				// })
			} else {
				if(zwxphone=='13879171577'||zwxphone==='18279124451'||zwxphone==='13970942033'){
					this.showSym = true
				}

		
				// this.lastDeviceInfo();
				// this.times(); //加载定时任务
			}
		}

	}
</script>

<style scoped lang="scss">
	.outTime-class{
		color: grey !important;
	}
	.mask {
		position: fixed;
		z-index: 166;
		margin: 15rpx 15rpx;
		padding: 15rpx 30rpx;
		box-sizing: border-box;
		bottom: 70rpx;
		background: #F6F7FB;
		border-radius: 6rpx;
		height: 666rpx;
		width: 720rpx;
	}
	.jiayi{
		color:#2397ee;
	}
	.dianliang{
		color:#16af19; 
			} 	
			.chuhan{color:orange; } 	
			.jianyi{color: #f91d14}
				.yichang{color:grey}
	page {
		width: 100%;
		height: 100%;
		background-color: white;
	}

	.title_main {
		width: 750rpx;
		height: 200rpx;
		line-height: 240rpx;
		text-align: center;
		font-size: 24px;
	}

	// 宝宝信息
	.first_join {
		display: flex;
	}

	.Infromation {
		flex: 1;
		width: 300rpx;
		display: flex;
	}

	.portrait_join {
		flex: 2;
		display: inline-block;
		width: 150rpx;
		height: 150rpx;
	}

	.portrait_join>image {
		display: inline-block;
		width: 150rpx;
		height: 150rpx;
		margin-left: 30rpx;
		border-radius: 50%;

		box-shadow: 1px 1px 2px rgb(228, 227, 227), 0 0 5px rgb(228, 227, 227), 0 0 1px rgb(228, 227, 227);

		box-shadow: 1px 1px 2px rgb(228, 227, 227), 0 0 5px rgb(228, 227, 227), 0 0 1px rgb(228, 227, 227);
	}

	.data_join {
		flex: 1;
		display: inline-block;
		padding-top: 30rpx;
		height: 150rpx;
		font-size: 32rpx;
		position: relative;
	}

	// 历史数据
	.History {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-right:12px;
	}

	.History>image {
	
		width: 50rpx;
		height: 50rpx;
		
	}

	.History>view {
		
		color: #596FE8;
		font-size: 11PX;
	}

	.container {
		text-align: center;
		width: 100%;
		height: 280px;
		position: relative;
	}

	.Centigrade {
		font-size: 48rpx;
		position: relative;
		height: 20rpx;
	}


	.temperature {
		font-size: 100rpx;
	}

	.temp {
		font-size: 50rpx;
	}

	#firstCanvas {
		margin: 0 auto;
		position: absolute;
		top: -10%;
		left: 50%;
		transform: translateX(-50%);
	}

	// 圆环刻度
	.percentage {
		color: #666;
		margin-top: 20rpx;
		text-align: center;
		font-size: 30rpx;
		position: absolute;
		top: 35%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	// 时间
	.time_join {
		margin-bottom: 50rpx;
		width: 750rpx;
		text-align: center;
		color: #666666;
	}

	// 状态
	.state {
		display: flex;
		height: 100rpx;
		margin: 20rpx;
	}

	.state>view {
		flex: 1;
		border-radius: 10rpx;
		box-shadow: 1px 1px 2px rgb(228, 227, 227), 0 0 1px rgb(228, 227, 227), 0 0 1px rgb(228, 227, 227)
	}

	.model_join {
		padding: 10rpx;
		color: #596fe8;
		font-size: 12px;
		text-align: center;
		margin-right: 15rpx;
	}

	.model_join>image {
		width: 40rpx;
		height: 30rpx;
	}

	.line_join {
		padding: 10rpx;
		color: #596fe8;
		font-size: 12px;
		text-align: center;
		margin-right: 15r
	}

	.quantity_join {
		padding: 10rpx;
		color: #596fe8;
		font-size: 12px;
		text-align: center;
		margin-right: 15rpx;
	}

	.voice_join {
		padding: 10rpx;
		color: #596fe8;
		font-size: 12px;
		text-align: center;
		margin-right: 0rpx;
	}


	// 提示
	.Tips {
		display: flex;
		margin: 20rpx;
		margin-top: 50rpx;
	}

	.Tips>view {
		height: 250rpx;
		background-color: #F6F7FB;
		border-radius: 30rpx;

		box-shadow: 1px 1px 2px rgb(228, 227, 227), 0 0 5px rgb(228, 227, 227), 0 0 1px rgb(228, 227, 227);
	}

	// 温馨提示
	.tips_join {
		flex: 1;
		padding: 20rpx;
	}

	.tips_join>image {
		width: 40rpx;
		height: 40rpx;
	}

	.tips_join>view {
		// margin-top: 10rpx;
		text-align: center;
		font-size: 16px;
		color: #253DC2;
	}

	.tips_join>text {
		font-size: 16px;
		font-weight: bold;
		margin-left: 10rpx;
		color: #FF5310;
	}

	// 今日简报
	.briefing_join {
		flex: 1;
		margin-left: 20rpx;
		padding: 30rpx;
	}

	.briefing_join>image {
		width: 40rpx;
		height: 40rpx;
	}

	.briefing_join>view {
		text-align: center;
		margin-top: 10rpx;
		font-size: 16px;
		color: #253DC2;
	}

	.briefing_join>text {
		color: #152EB7;
		font-weight: bold;
		font-size: 16px;
		margin-left: 10rpx;
	}
</style>
